package org.brisling.medical.queryService;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.brisling.authorize.shiro.ShiroSecurityService;
import org.brisling.base.domain.ListDomain;
import org.brisling.base.service.AbstractBaseQueryService;
import org.brisling.common.ConstSysParam;
import org.brisling.common.SysConfig;
import org.brisling.medical.domain.InpatientDiagnosis;
import org.brisling.sysman.queryService.QueryDictionaryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

/**
 * 
 * <p>Title: QueryInpatientDiagnosisService</p>
 * <p>Description: 住院诊断查询服务类</p>
 * <p>Company: tongking</p>
 * @author jackson wang
 * @since 1.0
 * @version 1.0
 * @date 2017年2月21日 上午11:44:41
 */
@RestController
@RequestMapping("/medicalInpatientDiagnosis/query")
public class QueryInpatientDiagnosisService extends AbstractBaseQueryService<InpatientDiagnosis>{
	
	
	
	@Autowired
	private ShiroSecurityService shiroSecurityService;
	@Autowired
	private QueryDictionaryService dicService;
	public QueryInpatientDiagnosisService(){
		this.moduleName = ConstSysParam.MODULE_INPATIENT;
		this.subSystem = ConstSysParam.SUBSYSTEM_MEDICAL;
		this.tableName = ConstSysParam.VIEW_PREFIX +this.getTableName(InpatientDiagnosis.class);
		this.clazz = InpatientDiagnosis.class;
		
		typeMap = this.getTypeMap(clazz);
		
		
		orderMap.put("outhospitalat","desc");			
		
	}
	
	@PersistenceContext(unitName=ConstSysParam.SUBSYSTEM_SYSMAN)
	@Autowired
	protected void setEntityManager(EntityManager entityManager){
		this.entityManager = entityManager;		
	}
	
	@RequestMapping("/mainPage.action")
	public ModelAndView getMainPage(){
		return this.getBizMainPage();
	}
	
	/* (non-Javadoc)
	 * @see org.brisling.service.sysman.DepartmentServiceInf#getEditPage()
	 */
	@RequestMapping("/editPage.action")
	public ModelAndView getEditPage(){
		return this.getBizEditPage();
	}
	
	@RequestMapping("/bizInfoPage.action")
	public ModelAndView getBizInfoPage(){
		return new ModelAndView("/medical/medical_inpatient/popMain");
	}
	
	@RequestMapping("/getListDomain.action")
	public ListDomain<InpatientDiagnosis> getListDomain(@RequestBody(required=false) String body){	
		
		return super.getListDomainByConditionAndOrder(body, typeMap, orderMap,true);
		
		
	}
	
	/**
	 * 获取业务数据统计值
	 * @param body
	 * @return
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping("/getBizCount.action")
	public Long getBizCount(@RequestBody(required=false)String body){
		Map<String,Object> map = this.getBodyParam(body);
		String userid = shiroSecurityService.getCurrentUserIdentify();
		Map<String,String> paramMap = (Map<String, String>) map.get(ConstSysParam.CONDITION_MAP_KEY);
		return  this.getBizCnt(paramMap,userid);
	}
	
	
	public Long getBizCnt(Map<String,String> paramMap,String userid){
		if(!this.isSuperDept(userid,ConstSysParam.QUERY_ALL, "query_medical_all")){
			String deptids = getUserDeptids(userid);
			paramMap.put("doct_depart_code_in", deptids);
		}
		return  super.getBizCount(paramMap,null,null,null);
	}
	
	/**
	 * 获取业务数据统计值
	 * @param body
	 * @return
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping("/getBizListDomain.action")
	public ListDomain<InpatientDiagnosis> getBizListDomain(@RequestBody(required=false)String body){
		String sql = dicService.getSqlByBizcode("medical_inpatient_bizlist");
		String userid = shiroSecurityService.getCurrentUserIdentify();
		Map<String,Object> map = this.getBodyParam(body);
		Map<String,String> conditionMap = (Map<String, String>) map.get(ConstSysParam.CONDITION_MAP_KEY);
		
		String condition1 = "";
		String condition2 = "";
		if(conditionMap!=null){
			
			if(conditionMap.containsKey("outhospitalat_start") && conditionMap.containsKey("outhospitalat_end")){
				condition1 = String.format(SysConfig.getConfig("dateGeTemplate"),"outhospitalat",conditionMap.get("outhospitalat_start"));
				
				condition1 = " where " +condition1 + " and " +String.format(SysConfig.getConfig("dateLeTemplate"),"outhospitalat",conditionMap.get("outhospitalat_end"));
			}
			
			if(conditionMap.containsKey("inquiry_item_code")){
				condition2 =" where " + String.format(SysConfig.getConfig("strTemplate"),"inquiry_item_code",conditionMap.get("inquiry_item_code"));				
			}
		}
		
		sql = String.format(sql, condition1,condition2,"%1$s");
		
		map.put(ConstSysParam.CONDITION_MAP_KEY, new HashMap<String,String>());
		if(!this.isSuperDept(userid,ConstSysParam.QUERY_ALL, "query_medical_all")){
			map = this.addDeptConditionToMap(userid,map, "doct_depart_code");			
		}
		return super.getListDomainByConditionAndOrder(sql,map, typeMap, orderMap,true);
	}
	
	@RequestMapping("/getList.action")
	public List<InpatientDiagnosis> getList(@RequestParam(value="page",required=false) Integer page,
			@RequestParam(value="rows",required=false) Integer rows,
			@RequestParam(value="deptid",required=false) Integer deptid,
			@RequestParam(value="sort",required=false) String sort){		
		
		StringBuilder sb = new StringBuilder();
		String sql = "";
		if(deptid!=null){
			String whereCorse=String.format(sb.append("\"deptid\" = %1$d").toString(),deptid);
			sql = String.format(this.TW_SQL, this.tableName,whereCorse);
		}else{
			sql = String.format(this.T_SQL, this.tableName);
		}
		
		return super.getPagedList(page,rows,sql);
	}
	
	/**
	 * 根据用户id查找用户信息
	 * @param id	用户id
	 * @return 用户信息记录 
	 */
	@RequestMapping("/getOne.action")
	public InpatientDiagnosis getOne(@RequestParam(value="id",required=false) Long id){
		return super.getOne(id);
	}
	
	
	/**
	 * 根据用户id查找用户信息
	 * @param id	用户id
	 * @return 用户信息记录 
	 */
	@RequestMapping("/getDiagnosis.action")
	public InpatientDiagnosis getDiagnosis(@RequestParam(value="id",required=false) String id){
		
		String sql = String.format(this.TW_SQL,this.tableName," patient_id="+id);
		List<InpatientDiagnosis> lists = this.getAllList(sql);
		
		//入院、出院诊断
		String diagnosis_in = "";
		String diagnosis_out = "";
		
		
		if(lists!=null && lists.size()>0){
			for(InpatientDiagnosis i:lists){
				if(i!=null && i.getDisease()!=null){
					
					//缓存诊断信息
					if(i.getDiagnosis_type().compareTo("入院诊断")==0){
						diagnosis_in =diagnosis_in==""?i.getDisease():diagnosis_in+","+i.getDisease();
						
					}else{
						diagnosis_out =diagnosis_out==""?i.getDisease():diagnosis_out+","+i.getDisease();
						
					}
				}
			}
			
			
			
			lists.get(0).setDiagnosis_in(diagnosis_in);
			lists.get(0).setDiagnosis_out(diagnosis_out);
			return lists.get(0);
		}
		return null;
	}
	
	/**
	 * 根据用户唯一编码查找用户信息
	 * @param identify	用户唯一编码
	 * @return 用户信息记录
	 */
	@RequestMapping("/getOneByIdentify.action")
	public InpatientDiagnosis getOneByIdentify(@RequestParam(value="identify",required=false) String identify){	
		return super.getOneByIdentify(identify);
	}
	
	@RequestMapping("/getOneByField.action")
	public InpatientDiagnosis getOneByField(@RequestParam(value="field",required=false) String field,@RequestParam(value="fieldVal",required=false) String fieldVal){	
		return this.getOneByIdentify(field,fieldVal);
	}
	
	protected InpatientDiagnosis getOneByIdentify(String identify,String value){
		
		String _identify = "identify";
		
		_identify = identify==null?_identify:identify;
		StringBuilder sb = new StringBuilder();
		String sql = null;
		
		if(identify!=null){
			String whereCorse=String.format(sb.append("%1$s = \'%2$s\'").toString(),_identify,value);
			sql = String.format("select * from (select I.DOCT_DEPART_CODE, I.DOCT_DEPART_NAME, I.DOCT_CODE, I.HOSPITAL_CODE, I.HOSPITAL_NAME, I.INHZOSPITALAT, I.INPATIENT_NO, I.INPATIENT_TYPE, I.IS_COMMENT, I.IS_DEATH, I.OUTHOSPITALAT, I.PATIENT_BIRTH, I.PATIENT_ID, I.PATIENT_NAME, I.PATIENT_NO, I.PATIENT_SEX, I.ZYHM, U.NAME doct_name from v_medical_inpatient i left join v_sysman_user u on i.doct_code = u.doct_code) WHERE %2$s", this.tableName,whereCorse);
			Query query= entityManager.createNativeQuery(sql);
			
			return (InpatientDiagnosis) super.reflectObjectMap(clazz, getSingalQueryResult(query),null);
		}
		return null;
		
	}
	public ListDomain<InpatientDiagnosis> getMyListDomain(String sql){	
		return super.getSqlListDomain(sql);
	}
	
	/**
	 * 按照患者编码查询患者住院记录，
	 * @param patient_no	患者编码
	 * @return
	 */
	public List<InpatientDiagnosis> getListByPatientNo(String patient_no){
		
		if(patient_no!=null){
		String sql = "select * from %1$s where patient_no = '%2$s' order by inhzospitalat desc";
		sql = String.format(sql, this.tableName,patient_no);
		return super.getAllList(sql);
		}else{
			return null;
		}
	}
}
